<template>
  <div class="map" id="map"></div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import * as Cesium from 'cesium'
import axios from 'axios'
let earth = null
onMounted(() => {
  // 创建地球
  earth = new Cesium.Viewer('map', {
    selectionIndicator: false,
    geocoder: false,
    baseLayerPicker: false,
    infoBox: false,
    homeButton: false,
    animation: false,
    timeline: false,
    shouldAnimate: true,
    sceneModePicker: false,
    scene3DOnly: true,
    fullscreenButton: false,
    navigationHelpButton: false,
  })
  earth._cesiumWidget._creditContainer.style.display = 'none'
  // 叠加影像服务
  var imgMap = new Cesium.UrlTemplateImageryProvider({
    url: 'https://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=ff37f45b78321a410b4771c3fd14d66d',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    maximumLevel: 18
  })
  earth.imageryLayers.addImageryProvider(imgMap)

  // 叠加国界服务
  var iboMap = new Cesium.UrlTemplateImageryProvider({
    url: 'https://t{s}.tianditu.gov.cn/DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=ff37f45b78321a410b4771c3fd14d66d',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    maximumLevel: 10
  })
  earth.imageryLayers.addImageryProvider(iboMap)
  earth.scene.globe.depthTestAgainstTerrain = true
  earth.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(113.764043, 34.005325, 100000000)
  })
  setCzml('GPS')
})
const setCzml = async (type) => {
  let color = []
  switch (type) {
    case 'BDS':
      color = ['90', '224', '140', 255]
      break
    case 'GPS':
      color = ['237', '106', '63', 255]
      break
    case 'GLONASS':
      color = ['65', '209', '243', 255]
      break
    case 'Galileo':
      color = ['249', '136', '236', 255]
      break
  }

  await axios
    .get('/czml/' + type + '.czml')
    .then((res) => {
      let czml = res.data
      czml = czml.map((item) => {
        if (item.label) {
          if (item.label.text.indexOf('(') !== -1) {
            item.label.text = item.label.text.split('(')[1].split(')')[0]
          }
        }
        if (item.path) {
          item.path.material.solidColor.color = {
            rgba: color
          }
          item.label.fillColor = {
            rgba: color
          }
        }

        return item
      })
      earth.dataSources.add(Cesium.CzmlDataSource.load(czml))
    })
    .catch((error) => {
      console.log(error)
    })
}

onUnmounted(() => {
  earth.destroy()
})
</script>

<style scoped lang="scss">
.map {
  width: 100%;
  height: 100%;
}
</style>